package com.aw.guiguzi.widgets

import android.app.Activity
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.text.method.ScrollingMovementMethod
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.CompoundButton
import android.widget.PopupWindow
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Spinner
import android.widget.Switch
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.aw.baselib.base.AwBaseConstant
import com.aw.baselib.util.AwDataUtil
import com.aw.baselib.util.AwDisplayUtil
import com.aw.baselib.util.AwPopupwindowUtil
import com.aw.baselib.util.AwRecyclerViewUtil
import com.aw.baselib.util.AwToastUtil
import com.aw.guiguzi.R
import com.aw.guiguzi.adapter.NumEncloseAdapter
import com.aw.guiguzi.adapter.NumEncloseResultAdapter
import com.aw.guiguzi.base.MyApp
import com.aw.guiguzi.bean.NumEncloseBean
import com.aw.guiguzi.constants.MyConstant
import com.aw.guiguzi.enums.NumBettingEnums
import com.aw.guiguzi.event.EventRefreshCalResultType
import com.aw.guiguzi.util.AppCacheUtil
import com.aw.guiguzi.util.CalResultUtil.getEncloseSpecialNumResult
import com.aw.guiguzi.util.CommonUtil.isAllow
import com.chad.library.adapter.base.BaseQuickAdapter
import org.greenrobot.eventbus.EventBus
import java.util.Arrays

class NumEnclosePopupWindow(
    private val mActivity: Activity,
    allNums: String,
    dismissListener: OnDismissListener?
) : PopupWindow() {
    private val contentView: View
    private val mAdapter: NumEncloseAdapter
    private val mResultAdapter: NumEncloseResultAdapter
    private val rcv_dataResult: RecyclerView
    private var mList: MutableList<NumEncloseBean> = ArrayList()
    private var mResultList: MutableList<String> = ArrayList()
    private var mResultToShowList: MutableList<String> = ArrayList()
    private var calNums: String

    init {
        mList = MyApp.mAllNumEncloseList
        contentView = View.inflate(mActivity, R.layout.view_popupwindow_num_enclose, null)
        val rcv_data = contentView.findViewById<View>(R.id.rcv_data) as RecyclerView
        rcv_dataResult = contentView.findViewById<View>(R.id.rcv_dataResult) as RecyclerView
        val switch_bettingDetail = contentView.findViewById<Switch>(R.id.switch_bettingDetail)
        val rg_limitLength = contentView.findViewById<RadioGroup>(R.id.rg_limitLength)
        val rBtn_limitAll = contentView.findViewById<RadioButton>(R.id.rBtn_limitAll)
        val rBtn_limit1 = contentView.findViewById<RadioButton>(R.id.rBtn_limit1)
        val rBtn_limit2 = contentView.findViewById<RadioButton>(R.id.rBtn_limit2)
        val tv_config = contentView.findViewById<Spinner>(R.id.tv_config)
        val tv_allNums = contentView.findViewById<TextView>(R.id.tv_allNums)
        val tv_calNums = contentView.findViewById<TextView>(R.id.tv_calNums)
        val tv_result = contentView.findViewById<TextView>(R.id.tv_result)
        val tv_customConfig = contentView.findViewById<TextView>(R.id.tv_customConfig)
        tv_result.movementMethod = ScrollingMovementMethod.getInstance()
        calNums = allNums
        if (AppCacheUtil.getLimitType() == MyConstant.SWITCH_ALL) {
            rBtn_limitAll.isChecked = true
        } else if (AppCacheUtil.getLimitType() == MyConstant.SWITCH_LIMIT1) {
            rBtn_limit1.isChecked = true
        } else if (AppCacheUtil.getLimitType() == MyConstant.SWITCH_LIMIT2) {
            rBtn_limit2.isChecked = true
        }
        rBtn_limit1.text = "后" + AppCacheUtil.getAnalysisLengthCustom() + "位"
        rBtn_limit2.text = "后" + AppCacheUtil.getLimitStatisticsCountCustom() + "位"
        tv_calNums.text = getCalNums(allNums)
        tv_allNums.text = "全数: $allNums"
        mAdapter = NumEncloseAdapter()
        AwRecyclerViewUtil.setRecyclerViewGridlayout(
            mActivity,
            rcv_data,
            mAdapter,
            5,
            AwDisplayUtil.dip2px(mActivity, 2f)
        )
        mAdapter.addAllData(mList)
        for (itemBean in mList) {
            itemBean!!.isChecked = false
        }
        mAdapter.notifyDataSetChanged()
        mResultAdapter = NumEncloseResultAdapter()
        AwRecyclerViewUtil.setRecyclerViewLinearlayout(
            mActivity,
            rcv_dataResult,
            mResultAdapter,
            false
        )
        mResultAdapter.addAllData(mResultToShowList)
        tv_customConfig.text =
            "宝石" + mList[0].gemstoneCount + "，银" + mList[0].silverCount + "，皮" + mList[0].skinCount
        val defalutIndex = defaultConfigCountIndex
        tv_customConfig.visibility = if (defalutIndex == 0) View.VISIBLE else View.GONE
        tv_config.setSelection(defalutIndex)
        tv_config.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>,
                view: View,
                position: Int,
                id: Long
            ) {
                tv_customConfig.visibility = if (position == 0) View.VISIBLE else View.GONE
                setListItemCount(parent.selectedItem as String)
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        switch_bettingDetail.setOnCheckedChangeListener { buttonView: CompoundButton?, isChecked: Boolean ->
            switch_bettingDetail.setTextColor(mActivity.resources.getColor(if (isChecked) R.color.teal_700 else com.aw.baselib.R.color.color_A5A5A5))
            if (AwDataUtil.isEmpty(mResultList)) {
                return@setOnCheckedChangeListener
            }
            mResultToShowList = ArrayList()
            if (isChecked) {
                AwToastUtil.show("已开启详情，仅保留一条最近计算数据")
                mResultToShowList.addAll(mResultList)
            } else {
                mResultToShowList.add(mResultList[0])
                mResultToShowList.add(mResultList[1])
            }
            mResultAdapter.addAllData(mResultToShowList)
        }
        rg_limitLength.setOnCheckedChangeListener { group: RadioGroup?, checkedId: Int ->
            if (!isAllow) {
                return@setOnCheckedChangeListener
            }
            when (checkedId) {
                R.id.rBtn_limitAll -> AppCacheUtil.setLimitType(MyConstant.SWITCH_ALL)
                R.id.rBtn_limit1 -> AppCacheUtil.setLimitType(MyConstant.SWITCH_LIMIT1)
                R.id.rBtn_limit2 -> AppCacheUtil.setLimitType(MyConstant.SWITCH_LIMIT2)
            }
            EventBus.getDefault().postSticky(EventRefreshCalResultType(null))
            tv_calNums.text = getCalNums(allNums)
            toSubmit(switch_bettingDetail.isChecked, false)
        }
        mAdapter.setOnItemClickListener { adapter: BaseQuickAdapter<*, *>, view: View?, position: Int ->
            val itemBean = adapter.getItem(position) as NumEncloseBean?
            for (bean in mList) {
                if (bean!!.resultNumber == itemBean!!.resultNumber) {
                    bean.isChecked = !itemBean.isChecked
                } else {
                    bean.isChecked = false
                }
            }
            mAdapter.notifyDataSetChanged()
            toSubmit(switch_bettingDetail.isChecked, false)
        }
        setContentView(contentView)
        this.width = ViewGroup.LayoutParams.MATCH_PARENT
        this.height = ViewGroup.LayoutParams.WRAP_CONTENT
        this.animationStyle = com.aw.baselib.R.style.sytle_anim_pop_in_out
        this.isFocusable = true
        this.isTouchable = true
        this.isOutsideTouchable = true
        setBackgroundDrawable(BitmapDrawable())
        this.update()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.overlapAnchor = true
        }
        if (dismissListener == null) {
            setOnDismissListener {
                val lp = mActivity.window.attributes
                lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_NORMAL
                mActivity.window.attributes = lp
            }
        } else {
            setOnDismissListener(dismissListener)
        }
    }

    private fun getCalNums(allNums: String): String {
        val customScreenOutPre = AppCacheUtil.getAnalysisNumsScreenOutPreCustom()
        val sb = StringBuffer()
        if (AppCacheUtil.getLimitType() == MyConstant.SWITCH_LIMIT1) {
            if (allNums.length > AppCacheUtil.getAnalysisLengthCustom()) {
                calNums = allNums.substring(allNums.length - AppCacheUtil.getAnalysisLengthCustom())
            }
            sb.append("最后" + AppCacheUtil.getAnalysisLengthCustom() + "位：")
        } else if (AppCacheUtil.getLimitType() == MyConstant.SWITCH_LIMIT2) {
            if (allNums.length > AppCacheUtil.getLimitStatisticsCountCustom()) {
                calNums =
                    allNums.substring(allNums.length - AppCacheUtil.getLimitStatisticsCountCustom())
            }
            sb.append("最后" + AppCacheUtil.getLimitStatisticsCountCustom() + "位：")
        } else {
            sb.append("全部数字")
            if (AppCacheUtil.isNumsScreenOutPre() && allNums.length > customScreenOutPre) {
                sb.append("，筛除前" + customScreenOutPre + "位后：")
                //如果开启了前minLengthToScreenOut位过滤且总长度大于minLengthToScreenOut位, 以该过滤为准
                calNums = allNums.substring(customScreenOutPre, allNums.length)
            }
        }
        if (!sb.toString().contains("全部数字") || sb.toString().contains("筛除前")) {
            sb.append(calNums)
        }
        return sb.toString()
    }

    private fun toSubmit(isChecked: Boolean, needHint: Boolean) {
        val selectList: MutableList<NumEncloseBean?> = ArrayList()
        for (itemBean in mList) {
            if (itemBean!!.isChecked) {
                selectList.add(itemBean)
            }
        }
        if (AwDataUtil.isEmpty(selectList)) {
            if (needHint) {
                AwToastUtil.showShort(mActivity, "请至少选择一项数据")
            }
            return
        }
        mResultList = getEncloseSpecialNumResult(selectList[0]!!, calNums)
        if (isChecked) {
            mResultToShowList = ArrayList()
            mResultToShowList.addAll(mResultList)
        } else {
            mResultToShowList.add(mResultList[0])
            //            mResultToShowList.add(mResultList.get(1));
        }
        mResultAdapter.addAllData(mResultToShowList)
        if (!isChecked) {
            rcv_dataResult.scrollToPosition(mResultToShowList.size - 1)
        }
    }

    private val defaultConfigCountIndex: Int
        private get() {
            val list = Arrays.asList(*mActivity.resources.getStringArray(R.array.config_count))
            return list.indexOf(AppCacheUtil.getBettingConfigCount())
        }

    private fun setListItemCount(name: String) {
        if (AwDataUtil.isEmpty(mList)) {
            return
        }
        AppCacheUtil.setBettingConfigCount(name)
        for (itemBean in mList) {
            if (name == NumBettingEnums.MODE_1_1_10.name) {
                itemBean!!.silverCount = 1
                itemBean.skinCount = 1
                itemBean.gemstoneCount = 10
            } else if (name == NumBettingEnums.MODE_1_1_20.name) {
                itemBean!!.silverCount = 1
                itemBean.skinCount = 1
                itemBean.gemstoneCount = 20
            } else if (name == NumBettingEnums.MODE_1_1_40.name) {
                itemBean!!.silverCount = 1
                itemBean.skinCount = 1
                itemBean.gemstoneCount = 40
            } else if (name == NumBettingEnums.MODE_2_2_20.name) {
                itemBean!!.silverCount = 2
                itemBean.skinCount = 2
                itemBean.gemstoneCount = 20
            } else if (name == NumBettingEnums.MODE_2_2_40.name) {
                itemBean!!.silverCount = 2
                itemBean.skinCount = 2
                itemBean.gemstoneCount = 40
            } else if (name == NumBettingEnums.MODE_3_3_30.name) {
                itemBean!!.silverCount = 3
                itemBean.skinCount = 3
                itemBean.gemstoneCount = 30
            } else if (name == NumBettingEnums.MODE_4_4_40.name) {
                itemBean!!.silverCount = 4
                itemBean.skinCount = 4
                itemBean.gemstoneCount = 40
            } else if (name == NumBettingEnums.MODE_5_5_50.name) {
                itemBean!!.silverCount = 5
                itemBean.skinCount = 5
                itemBean.gemstoneCount = 50
            } else if (name == NumBettingEnums.MODE_5_5_100.name) {
                itemBean!!.silverCount = 5
                itemBean.skinCount = 5
                itemBean.gemstoneCount = 100
            } else if (name == NumBettingEnums.MODE_10_10_100.name) {
                itemBean!!.silverCount = 10
                itemBean.skinCount = 10
                itemBean.gemstoneCount = 100
            } else if (name == NumBettingEnums.MODE_10_10_200.name) {
                itemBean!!.silverCount = 10
                itemBean.skinCount = 10
                itemBean.gemstoneCount = 200
            } else {
                val bettingCustomArrays = AppCacheUtil.getBettingCustom().split("/".toRegex())
                    .dropLastWhile { it.isEmpty() }
                    .toTypedArray()
                itemBean!!.silverCount = AwDataUtil.getIntValue(bettingCustomArrays[0])
                itemBean.skinCount = AwDataUtil.getIntValue(bettingCustomArrays[1])
                itemBean.gemstoneCount = AwDataUtil.getIntValue(bettingCustomArrays[2])
            }
        }
    }

    /**
     * 展示窗口
     */
    fun show(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        this.showAsDropDown(parent, 0, 0)
    }

    fun showAsLocation(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        val windowPos = AwPopupwindowUtil.calculatePopWindowPos(parent, contentView)
        val xOff = 20 // 可以自己调整偏移
        windowPos[0] -= xOff
        showAtLocation(parent, Gravity.TOP or Gravity.START, windowPos[0], windowPos[1])
    }

    fun showAsLocationNoAlpha(parent: View?) {
        val windowPos = AwPopupwindowUtil.calculatePopWindowPos(parent, contentView)
        val xOff = 20 // 可以自己调整偏移
        windowPos[0] -= xOff
        showAtLocation(parent, Gravity.TOP or Gravity.START, windowPos[0], windowPos[1])
    }

    fun showAsLocationBottom(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        showAtLocation(parent, Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, 0, 0)
    }
}